
from sys import exit
from time import sleep

from config import (
    REFERRAL_DATABASE_FILE_PATH,
    FROM_VERIFICATION_MAIL,
    SUBJECT_VERIFICATION_MAIL,
    REFERRAL_CODE,
)
import db
from steps import *
from utils import *


def create_account(referral_code=REFERRAL_CODE):

    account_data = {
        'alliance_name': get_random_alliance_name(),
        'cookies': None,
        'email': get_email(),
        'first_name': get_random_first_name(),
        'last_name': get_random_last_name(),
        'password': get_random_password(),
        'proxy': get_proxy(),
        'referral_code': referral_code,
        'registration_date': get_current_datetime(),
        'username': get_random_username(),
        'user_agent': get_random_user_agent(),
        'user_id': None,
        'wallet': get_random_wallet(),
    }

    logger.debug(account_data)

    get_server_time_result = get_server_time(
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent']
    )
    if get_server_time_result['status'] != 'success':
        logger.error(f'code: YcEp5ZdU;')
        return {'status': 'error'}
    server_time = get_server_time_result['data']['time']

    message = f'{{"created_on":"{server_time}"}}'
    wallet_sign_message_result = wallet_sign_message(
        message=message,
        private_key=account_data['wallet']['private_key']
    )
    connect_wallet_result = connect_wallet(
        wallet_address=account_data['wallet']['address'],
        signed_message=wallet_sign_message_result,
        message=message,
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent'],
    )
    if connect_wallet_result['status'] != 'success':
        logger.error(f'code: PMv2hJus;')
        return {'status': 'error'}
    account_data['cookies'] = connect_wallet_result['data']['cookies']
    account_data['user_id'] = connect_wallet_result['data']['account']['user_id']

    check_profile_result = check_profile(
        cookies=account_data['cookies'],
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent'],
    )
    if check_profile_result['status'] != 'success':
        logger.error(f'code: y92Gn7dJ;')
        return {'status': 'error'}

    choice_alliance_result = choice_alliance(
        alliance_id=account_data['alliance_name'],
        cookies=account_data['cookies'],
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent'],
    )
    if choice_alliance_result['status'] != 'success':
        logger.error(f'code: x3BwYnRq;')
        return {'status': 'error'}

    create_account_mission_result = create_account_mission(
        first_name=account_data['first_name'],
        last_name=account_data['last_name'],
        username=account_data['username'],
        password=account_data['password'],
        email=account_data['email'],
        referral_code=referral_code,
        cookies=account_data['cookies'],
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent'],
    )
    if create_account_mission_result['status'] != 'success':
        logger.error(f'code: H33zbqVr;')
        return {'status': 'error'}

    get_email_verification_url_result = get_email_verification_url(
        email=account_data['email'],
        _from=FROM_VERIFICATION_MAIL,
        subject=SUBJECT_VERIFICATION_MAIL,
        proxies=account_data['proxy']['proxies'],
        without_mail_id=None
    )
    if get_email_verification_url_result['status'] != 'success':
        if get_email_verification_url_result['status'] == 'again':
            pass
        else:
            logger.error('code: ZJU9uVz8')
    
    verify_email_result = verify_email_with_requests(
        url=get_email_verification_url_result['data']['url'],
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent'],
    )
    if verify_email_result['status'] != 'success':
        logger.error('code: 9rW2QC4w')
        return {'status': 'error'}

    check_profile_result = check_profile(
        cookies=account_data['cookies'],
        proxies=account_data['proxy']['proxies'],
        user_agent=account_data['user_agent'],
    )
    if check_profile_result['status'] != 'success':
        logger.error(f'code: Rk6ta6xk;')
        return {'status': 'error'}

    return {
        'status': 'success',
        'data': {
            'account': account_data
        }
    }


def main(i):

    logger.info(f'start create new referral: {i}')

    sleep(10)

    referral_account = create_account()
    if referral_account['status'] != 'success':
        logger.error('cannot create referral..')
        return {'status': 'error'}

    db.create_row(referral_account['data']['account'], _file=REFERRAL_DATABASE_FILE_PATH)

    logger.info(['Данные: ', referral_account['data']['account']])
    logger.info(f'Аккаунт {i} успешно создан!\n')


if __name__ == '__main__':

    logger.info('init databases')
    db.init(_file=REFERRAL_DATABASE_FILE_PATH)

    logger.info('run programm')

    for i in range(1, REFERRALS_COUNT+1):
        while True:
            sleep(5)
            try:
                main(i)
                break
            except Exception as e:
                logger.error(e)
            sleep(10)

    input('\npress enter to exit..')
